<template>
  <el-form inline>
    <el-form-item label="一级分类">
      <el-select :disabled="disabled" v-model="category1Id" placeholder="请选择" @change="handleCategory1Change">
        <el-option :label="item.name" :value="item.id" v-for="item in category1List" :key="item.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="二级分类">
      <el-select :disabled="disabled" v-model="category2Id" placeholder="请选择" @change="handleCategory2Change">
        <el-option :label="item.name" :value="item.id" v-for="item in category2List" :key="item.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="三级分类">
      <el-select :disabled="disabled" v-model="category3Id" placeholder="请选择" @change="handleCategory3Change">
        <el-option :label="item.name" :value="item.id" v-for="item in category3List" :key="item.id"></el-option>
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: 'CategorySelector',
  props: {
    disabled: Boolean
  },
  data () {
    return {
      category1Id: null,
      category2Id: null,
      category3Id: null,
      category1List: [],
      category2List: [],
      category3List: [],
    }
  },

  mounted () {
    // 获取一级分类列表显示
    this.getCategory1List()
  },

  methods: {
    async getCategory1List () {
      const result = await this.$API.category.getCategory1List()
      this.category1List = result.data
    },

    /* 
    处理选择新的一级分类id的监听回调
    请求获取对应的二级分类列表显示
    */
    async handleCategory1Change (category1Id) {
      // 清除二级和三级数据
      this.category2Id = null
      this.category3Id = null
      this.category2List = []
      this.category3List = []
      // 请求获取2级分类列表
      const result = await this.$API.category.getCategory2List(category1Id)
      this.category2List = result.data

      // 分发分类发生改变的事件
      console.log('---------1')
      this.$emit('categoryChange', {categoryId: category1Id, level: 1})
    },

    /* 
    处理选择新的二级分类id的监听回调
    请求获取对应的三级分类列表显示
    */
    async handleCategory2Change (category2Id) {
      // 清除三级数据
      this.category3Id = null
      this.category3List = []
      // 请求获取3级分类列表
      const result = await this.$API.category.getCategory3List(category2Id)
      this.category3List = result.data

      // 分发分类发生改变的事件
      this.$emit('categoryChange', {categoryId: category2Id, level: 2})
    },

    /* 
    处理选择新的三级分类id的监听回调
    */
    async handleCategory3Change (category3Id) {
      // 分发分类发生改变的事件
      this.$emit('categoryChange', {categoryId: category3Id, level: 3})
    }
  }
}
</script>
